source("startup.R")

############################################################
# THIS SCRIPT EVALUATES THE PERFORMANCE OF 1NN METHODS
############################################################

# the vector used to store recognition rates
recognitionRates = rep(0, 200)

for (k in kays_test){
  e <- getEigenVect(A %*% t(A),k) #get our basis functions

  # returns a function that takes input y and calculates the projected-distance
  # of x and y (i.e., distance in the eigenspace)
  dist <- function(x) { #euclidean distance between x and y (curried)
    z <- project(x,e)
    function(y) { sqrt(sum((z-project(y,e))^2))}
  }
  
  # function used for baseline measurement
  dist_non_project <- function(x) {
    function(y) { sqrt(sum((x-y)^2)) }
  }
  
  # prepare for nearest neighbor calculation (plug in B[,n] to calculate nearest neighbor of nth training example)  
  # takes a vector x and returns the index of the column vector in A
  # that is closest to x
  #closest <- function(x) (1:length(A[1,]))[getNN(A,dist(x))]
  
  closest_baseline <- function(x) (1:length(A[1,]))[getNN(A,dist_non_project(x))]
  
  # the number of correct classifications
  correct = 0
  
  totalElapsedTestTime = 0
  
  #c1 = rep("", 100)
  #c2 = rep("", 100)
  #i <- 1
  for (testDatum in TestData){
    print("===========TESTING NEW DATA POINT=============")
    # get the index of the vector in the training set that is closest to (mean-adjusted) testDatum 
    #closestIndex = closest(getVector(testDatum) - trainingMean)
    #print(sprintf("Test image path: %s", testDatum))
    
    closestIndex = closest_baseline(getVector(testDatum) - trainingMean)
    #print(sprintf("closestIndex: %d", closestIndex))
    
    # grab the name of the person in TrainingData[closestIndex]
    NNPersonName = gsub(".*faces/(.*)/.*", "\\1", TrainingData[closestIndex])
    print(sprintf("Name of individual in closest image to test image: %s", NNPersonName))
    
    print(sprintf("Nearest image path: %s", TrainingData[closestIndex]))
    
    # grab the name of the person in testDatum
    testPersonName = gsub(".*faces/(.*)/.*", "\\1", testDatum)
    print(sprintf("Actual name of individual in test image: %s", NNPersonName)) 
    
    # if correctly recognized the individual, add the recognition score
    if (NNPersonName == testPersonName){
      print(sprintf("Correctly classified %s", testDatum))
      correct = correct + 1
    } else {
      print(sprintf("Misclassified %s as %s", testPersonName, NNPersonName))
      print(sprintf("Test image path: %s", testDatum))
      print(sprintf("1NN training image path: %s", TrainingData[closestIndex]))
      #c1[i] = testDatum
      #c2[i] = TrainingData[closestIndex]
      #i = i + 1
    }
    print("===========END TESTING THIS DATA POINT=============")
  }
  
  recognitionRates[k] = correct / length(TestData)
  #avgElapsedTestTime = totalElapsedTestTime / length(TestData)
}